//! 指令解析实现
//! 
//! 解析汇编指令及其操作数列表

use crate::ast::*;
use crate::error::{AssemblerError, Result};
use crate::lexer::Token;
use super::core::Parser;
use super::operand::OperandParser;

pub trait InstructionParser {
    fn parse_instruction(&mut self) -> Result<Instruction>;
    fn is_jump_instruction(&self, name: &str) -> bool;
    fn skip_whitespace(&mut self);
}

impl InstructionParser for Parser {
    /// 解析指令
    fn parse_instruction(&mut self) -> Result<Instruction> {
        let (line, _) = self.lexer.position();
        
        let name = match &self.current_token {
            Token::Identifier(name) => {
                let name = name.clone();
                self.advance()?;
                name
            }
            _ => {
                let (line, column) = self.lexer.position();
                return Err(AssemblerError::ParseError {
                    message: "期望指令名称".to_string(),
                    line,
                    column,
                });
            }
        };

        let mut operands = Vec::new();

        // 解析操作数列表
        while !self.check_token(&Token::Newline) && !self.check_token(&Token::Eof) {
            // 跳过逗号
            if self.check_token(&Token::Comma) {
                self.advance()?;
                self.skip_whitespace();
            }

            // 根据指令类型解析操作数
            let operand = if self.is_jump_instruction(&name) {
                // 跳转指令的操作数可能是标签
                self.parse_jump_operand()?
            } else {
                self.parse_operand()?
            };
            
            operands.push(operand);

            // 如果下一个是换行或文件结束，停止
            if self.check_token(&Token::Newline) || self.check_token(&Token::Eof) {
                break;
            }
        }

        Ok(Instruction {
            name,
            operands,
            line,
        })
    }

    /// 跳过空白（但保留换行符）
    fn skip_whitespace(&mut self) {
        // 这个功能在词法分析器中已经处理了
    }

    /// 检查是否为跳转指令
    fn is_jump_instruction(&self, name: &str) -> bool {
        matches!(name, 
            "跳转" | "调用" |
            "等于跳转" | "不等于跳转" | "大于跳转" | "大于等于跳转" | 
            "小于跳转" | "小于等于跳转" |
            "进位跳转" | "无进位跳转" | "溢出跳转" | "无溢出跳转" |
            "零跳转" | "非零跳转" | "符号跳转" | "无符号跳转" |
            "偶跳转" | "奇跳转" |
            "高于跳转" | "高于等于跳转" | "低于跳转" | "低于等于跳转" |
            "循环" | "等于循环" | "不等于循环"
        )
    }
}

